package com.leo.tool.jwt;

import java.util.Base64;
import java.util.Date;

import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Leo
 * @date 2019/06/29
 */
@Slf4j
public class Jwt {

	private static final String USER_ID = "userId";

	private static String secret = "123456";

	private static long expire = 3600000;

	public static void main(String[] args) {
		String userId = "717626659";
		String result = parse(compact(userId));
		Assert.isTrue(userId.equals(result));
		System.out.println("success");
	}

	public static String compact(String userId) {
		return Jwts.builder().claim(USER_ID, userId)
				.signWith(SignatureAlgorithm.HS256, Base64.getEncoder().encode(secret.getBytes()))
				.setNotBefore(new Date()).setExpiration(new Date(System.currentTimeMillis() + expire)).compact();
	}

	public static String parse(String token) {
		JwtParser jwtParser = Jwts.parser().setSigningKey(Base64.getEncoder().encode(secret.getBytes()));
		try {
			return jwtParser.parseClaimsJws(token).getBody().get(USER_ID).toString();
		} catch (Exception e) {
			log.error("parse token error:", e);
			throw new RuntimeException("parse token error");
		}
	}

}
